package com.example.recyclerviewdemo.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.recyclerviewdemo.R;

import java.util.ArrayList;
import java.util.List;

public class ListViewDemo extends AppCompatActivity {
    private ListView mListView;
    private List<Fruit> fruitList = new ArrayList<>();

    private String[] data = {
            "Apple", "Banana", "Orange", "WaterMelon", "Pear",
            "Apple1", "Banana1", "Orange1", "WaterMelon1", "Pear1",
            "Apple2", "Banana2", "Orange2", "WaterMelon2", "Pear2",
            "Apple3", "Banana3", "Orange3", "WaterMelon3", "Pear3",
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view_demo);
        initFruitList();
        FruitAdapter fruitAdapter = new FruitAdapter(ListViewDemo.this, R.layout.view_item, fruitList);
        mListView = findViewById(R.id.list_view);
        mListView.setAdapter(fruitAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(ListViewDemo.this, fruit.getName(), Toast.LENGTH_LONG).show();
            }
        });
    }

    //初始化fruit的数据
    private void initFruitList() {
        for (int i = 0; i < data.length; i++) {
            Fruit fruit = new Fruit(data[i], R.drawable.ic_launcher_foreground);
            fruitList.add(fruit);
        }
    }
}


